//
//  HomePoltController.m
//  厚积薄发
//
//  Created by 焦钟培 on 15-1-13.
//  Copyright (c) 2015年 侯振兴. All rights reserved.
//

#import "HomePoltController.h"
#import "ConnectModel.h"
#import "DetailBace.h"
#import "DetailModel.h"
#import <ShareSDK/ShareSDK.h>
#import "DengLuViewController.h"
#import "Masonry.h"
#import "WebColor.h"
#import "Reachability.h"

#define kBlueColor [UIColor colorWithRed:129/255.0 green: 198/255.0 blue: 221/255.0 alpha: 1.0]
#define DEFAULTS ([NSUserDefaults standardUserDefaults])
@interface HomePoltController ()

@end

@implementation HomePoltController
- (void)dealloc
{
    [_poltTitle release];
    [_alert release];
    [_button1 release];
    [_webView release];
    [super dealloc];
}
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    BOOL judge = [self judgeConnected];
    if (!judge) {
        
       UIButton *tiButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        tiButton.frame = CGRectMake(80, self.view.frame.size.height/2 - 30, self.view.frame.size.width - 160, 60);
        tiButton.backgroundColor = [UIColor grayColor];
        [tiButton setTitle:@"网络异常请重试" forState:UIControlStateNormal];
        [tiButton setTitleColor:[UIColor lightTextColor] forState:UIControlStateNormal];
        tiButton.layer.cornerRadius = 10;
        [tiButton addTarget:self action:@selector(dis) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:tiButton];
        return;
    }
    self.webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height)];
    NSURL *url = [NSURL URLWithString:_path];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [_webView loadRequest:request];
    [self.view addSubview:_webView];
    for (UIView *subView in _webView.scrollView.subviews) {
        subView.frame = CGRectMake(subView.frame.origin.x, subView.frame.origin.y - 54, subView.frame.size.width, subView.frame.size.height);
    }
    _webView.delegate = self;
    [_webView release];
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 64)];
    headView.backgroundColor = kBlueColor;
    [self.view addSubview:headView];
    [headView release];
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(10, 25, 30, 30)];
    [button setBackgroundImage:[UIImage imageNamed:@"fanhui5.png"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(disD) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    [button release];
    
    self.button1 = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width - 40, 25, 30, 30)];
    [_button1 setBackgroundImage:[UIImage imageNamed:@"shoucang1.png"] forState:UIControlStateNormal];
    [_button1 addTarget:self action:@selector(rightAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_button1];
    [_button1 release];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSInteger nid = [[user objectForKey:@"nid"] integerValue];
    DetailModel *model = [[DetailBace searchDetail:nid] firstObject];
    NSArray *array = [model.detail_tit componentsSeparatedByString:@"$$"];
    for (NSString *histroy in array) {
        NSString *judge = [histroy stringByReplacingOccurrencesOfString:@"**" withString:@""];
        if ([judge isEqualToString:_poltTitle]) {
            [_button1 setBackgroundImage:[UIImage imageNamed:@"shoucang2.png"] forState:UIControlStateNormal];
        }
    }
    
    UIButton *button2 = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width - 100, 25, 30, 30)];
    [button2 setBackgroundImage:[UIImage imageNamed:@"fenxiang.png"] forState:UIControlStateNormal];
    [button2 addTarget:self action:@selector(centerAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button2];
    [button2 release];
    
    UIButton *rRight = [[UIButton alloc] init];
    [rRight setBackgroundImage:[UIImage imageNamed:@"wenzi.png"] forState:UIControlStateNormal];
    rRight.frame = CGRectMake(self.view.frame.size.width - 160, 25, 30, 30);
    [rRight addTarget:self action:@selector(RrightAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:rRight];
    [rRight release];

    
    
    UIButton *bigger = [[UIButton alloc] initWithFrame:CGRectMake(-self.view.frame.size.width / 4, 80, self.view.frame.size.width / 4 - 20, 40)];
    [bigger setImage:[UIImage imageNamed:@"fangda1.png"] forState:UIControlStateNormal];
    bigger.layer.cornerRadius = 5;
    bigger.clipsToBounds = YES;
    bigger.tag = 1;
    [bigger setBackgroundImage:[UIImage imageNamed:@"lantian10.png"] forState:UIControlStateNormal];
    [bigger addTarget:self action:@selector(biggerButton) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:bigger];
    [bigger release];
    
    UIButton *smaller = [[UIButton alloc] initWithFrame:CGRectMake(-self.view.frame.size.width / 4, 80, self.view.frame.size.width / 4 - 20, 40)];
    smaller.backgroundColor = [WebColor hotPink];
    [smaller setImage:[UIImage imageNamed:@"wenzi1.png"] forState:UIControlStateNormal];
    [smaller setBackgroundImage:[UIImage imageNamed:@"lantian10.png"] forState:UIControlStateNormal];
    smaller.layer.cornerRadius = 5;
    smaller.clipsToBounds = YES;
    smaller.tag = 2;
    [smaller addTarget:self action:@selector(smallerButton) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:smaller];
    [smaller release];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.iamg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"shua.png"]];
    _iamg.center = CGPointMake(self.view.frame.size.width/2, self.view.frame.size.height/2);
    [self.view addSubview:_iamg];
    CABasicAnimation* rotationAnimation;
    rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI * 2.0 ];
    [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    rotationAnimation.duration = 2;
    rotationAnimation.RepeatCount = 10000;
    rotationAnimation.cumulative = NO;
    rotationAnimation.removedOnCompletion = NO;
    rotationAnimation.fillMode = kCAFillModeForwards;
    [_iamg.layer addAnimation:rotationAnimation forKey:@"rotation"];
    
}
- (void)RrightAction
{
    if (!_judge) {
        if (_buttonTag == 0) {
            _buttonTag = 2;
        }
        UIButton *button = (UIButton *)[self.view viewWithTag:_buttonTag];
        
        [UIView animateWithDuration:0.25 * _buttonTag animations:^{
            button.frame = CGRectMake(self.view.frame.size.width/2 * (_buttonTag - 1) + 50, 80, self.view.frame.size.width/4 - 20, 40);
            _buttonTag--;
            if (_buttonTag != 0) {
                [NSTimer scheduledTimerWithTimeInterval:0.25f target:self selector:@selector(RrightAction) userInfo:nil repeats:NO];
            }else{
                _judge = YES;
            }
            
        }];
    }else{
        [self releaseButton];
        _buttonTag = 0;
    }
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    [self currC];
    [_iamg removeFromSuperview];
}
- (void)biggerButton
{
    
    int numOfFont = [[DEFAULTS objectForKey:@"numOfFont"] intValue];
    if (numOfFont < 250) {
        numOfFont += 20;
        NSString * str = [NSString stringWithFormat:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '%d%%'", numOfFont];
        [self.webView stringByEvaluatingJavaScriptFromString:str];
        NSString * font = [NSString stringWithFormat:@"%d", numOfFont];
        [DEFAULTS setObject:font forKey:@"numOfFont"];
    }
    
}
- (void)currC
{
    int numOfFont = [[DEFAULTS objectForKey:@"numOfFont"] intValue];
    NSString * strings = [NSString stringWithFormat:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '%d%%'",numOfFont];
    [self.webView stringByEvaluatingJavaScriptFromString:strings];
    NSString * font = [NSString stringWithFormat:@"%d", numOfFont];
    [DEFAULTS setObject:font forKey:@"numOfFont"];
    [DEFAULTS setObject:font forKey:@"numOfFont"];
}
- (void)smallerButton
{
    int numOfFont = [[DEFAULTS objectForKey:@"numOfFont"] intValue];
    if (numOfFont > 60) {
        numOfFont -=20;
        NSString * str = [NSString stringWithFormat:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '%d%%'", numOfFont];
        [self.webView stringByEvaluatingJavaScriptFromString:str];
        NSString * font = [NSString stringWithFormat:@"%d", numOfFont];
        [DEFAULTS setObject:font forKey:@"numOfFont"];
    }
}
- (void)releaseButton
{
    _judge = NO;
    for (int i = 1; i < 5; i++) {
        UIButton *button = (UIButton *)[self.view viewWithTag:i];
        button.frame = CGRectMake(-self.view.frame.size.width/4, 80, self.view.frame.size.width/4 - 20, 40);
    }
}

- (BOOL)judgeConnected
{
    Reachability *reach = [Reachability reachabilityWithHostName:@"http://www.baidu.com"];
    NetworkStatus status = [reach currentReachabilityStatus];
    switch (status) {
        case NotReachable:
        {
            return NO;
        }
            break;
        case ReachableViaWiFi:
        {
            return YES;
        }
            break;
        case ReachableViaWWAN:
        {
            return YES;
        }
            break;
        default:
            break;
    }
}
- (void)disD
{
    [self dismissViewControllerAnimated:NO completion:nil];
}
#warning 收藏
- (void)rightAction
{
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSInteger nid = [[user objectForKey:@"nid"] integerValue];
    NSString *str = [user objectForKey:@"login"];
    if ([str isEqualToString:@"yes"]) {
        NSString *show = @"";
        DetailModel *model = [[DetailBace searchDetail:nid] firstObject];
        if (model.detail_tit.length == 0) {
            show = [NSString stringWithFormat:@"收藏成功"];
            [DetailBace updateDetail_tit:[NSString stringWithFormat:@"**%@",_poltTitle] detail_id:nid detail_http:[NSString stringWithFormat:@"**%@",_path]];
        }else{
            NSArray *array = [model.detail_tit componentsSeparatedByString:@"$$"];
            for (int i = 0; i < [array count]; i++) {
                NSString *tit = [[array objectAtIndex:i] stringByReplacingOccurrencesOfString:@"**" withString:@""];
                if ([tit isEqualToString:_poltTitle]) {
                    show = [NSString stringWithFormat:@"已收藏"];
                    break;
                }else if (i == [array count]-1){
                    show = [NSString stringWithFormat:@"收藏成功"];
                    NSString *poltTitle = [NSString stringWithFormat:@"**%@",_poltTitle];
                    NSString *path = [NSString stringWithFormat:@"**%@",_path];
                    [DetailBace updateDetail_tit:[NSString stringWithFormat:@"%@$$%@",poltTitle,model.detail_tit] detail_id:nid detail_http:[NSString stringWithFormat:@"%@$$%@",path,model.detail_http]];
                }
            }
        }
        
        self.alert = [[UIAlertView alloc] initWithTitle:@"提示" message:show delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
        [NSTimer scheduledTimerWithTimeInterval:2.0f target:self selector:@selector(timerAction:) userInfo:nil repeats:NO];
        
        [_button1 setBackgroundImage:[UIImage imageNamed:@"shoucang2.png"] forState:UIControlStateNormal];
        [_alert show];
        [_alert release];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"Rinse" object:self userInfo:nil];
        
    } else {
        UIAlertView *alert1 = [[UIAlertView alloc] initWithTitle:@"不好意思" message:@"请您先登陆" delegate:self cancelButtonTitle:@"登陆" otherButtonTitles:@"取消", nil];
        [alert1 show];
        [alert1 release];
        
    }
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        DengLuViewController *dengController = [[DengLuViewController alloc] init];
        [self presentViewController:dengController animated:YES completion:nil];
        dengController.view.frame = CGRectMake(0, 0, dengController.view.frame.size.width, 0);
        [dengController release];
    }
}


#warning 分享
- (void)centerAction
{
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *str = [user objectForKey:@"login"];
    _path = [NSString stringWithFormat:@"%@\n%@",_poltTitle,_path];
    if ([str isEqualToString:@"yes"]) {
        NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"haiyang" ofType:@"jpg"];
        id<ISSContent> publishContent = [ShareSDK content:_path
                                           defaultContent:@"测试一下" image:[ShareSDK imageWithPath:imagePath]title:@"ShareSDK"
                                                      url:@"http://www.mob.com" description:@"这是一条测试信息"
                                                mediaType:SSPublishContentMediaTypeNews];
        //创建弹出菜单容器
        
        id<ISSContainer> container = [ShareSDK container];
        
        id<ISSShareOptions> shareOptions = [ShareSDK defaultShareOptionsWithTitle:@"内容分型" oneKeyShareList:[NSArray defaultOneKeyShareList] qqButtonHidden:YES wxSessionButtonHidden:YES wxTimelineButtonHidden:YES showKeyboardOnAppear:YES shareViewDelegate:self friendsViewDelegate:self picViewerViewDelegate:nil];
        
        
        
        //弹出分享菜单
        [ShareSDK showShareActionSheet:container
                             shareList:nil
                               content:publishContent
                         statusBarTips:YES
                           authOptions:nil
                          shareOptions:shareOptions
                                result:^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
                                    
                                    if (state == SSResponseStateSuccess)
                                    {
                                        NSLog(NSLocalizedString(@"TEXT_ShARE_SUC", @"分享成功"));
                                    }
                                    else if (state == SSResponseStateFail)
                                    {
                                        NSLog(NSLocalizedString(@"TEXT_ShARE_FAI", @"分享失败,错误码:%d,错误描述:%@"), [error errorCode], [error errorDescription]);
                                    }
                                }];
    } else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"不好意思" message:@"请您先登陆" delegate:self cancelButtonTitle:@"登陆" otherButtonTitles:@"取消", nil];
        
        [alert show];
        [alert release];
    }
    
}


- (void)timerAction:(id)sender
{
    [_alert dismissWithClickedButtonIndex:0 animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
